import express from "express";
import cors from "cors";
import multer from "multer";
import fs from "fs";
import path from "path";
import mime from "mime-types";

const app = express();
const port = 3000;
const upload = multer({ dest: "uploads/" });

// 处理跨域请求
app.use(cors());
// 解析客户端请求中的JSON数据，解析后的对象将被添加到req.body
app.use(express.json());
// 启用对静态文件的服务
app.use("/uploads", express.static("uploads"));

app.get("/", (req, res) => {
  res.send("Hello World!");
});

// 上传
app.post("/upload", upload.single("file"), (req, res) => {
  const file = req.file;
  const md5 = req.body.md5;
  const newPath = path.join(path.dirname(file.path), md5);
  fs.renameSync(file.path, newPath);
  res.send({ code: 200 });
});

// 合并
app.post("/merge", async (req, res) => {
  const { md5, fileName } = req.body;
  await concatFiles(md5, fileName);
  res.send({ code: 200, msg: "合并成功", data: `/uploads/${fileName}` });
});

// 下载文件流
app.get("/download/:fileName", (req, res) => {
  const { fileName } = req.params;
  const file = path.join("./uploads", fileName);
  const type = mime.lookup(file);

  res.setHeader(
    "Content-disposition",
    "attachment; filename=" + encodeURIComponent(path.basename(file))
  );
  res.setHeader("Content-type", type);

  const filestream = fs.createReadStream(file);
  filestream.pipe(res);
});

app.listen(port, () => {
  console.log(`listening on port ${port}`);
});

// 合并切片的文件
async function concatFiles(fileChunks, name) {
  const filePath = path.join("./uploads", name);
  const writeStream = fs.createWriteStream(filePath);
  for (let i = 0; i < fileChunks.length; i++) {
    const chunkPath = path.join("./uploads", fileChunks[i]);
    const file = fs.createReadStream(chunkPath);
    file.pipe(writeStream, { end: false });
    // 等待当前文件读完再进行下一个
    await new Promise((resolve) => file.on("end", resolve));
    fs.unlink(chunkPath, (e) => {
      if (e) {
        console.error("删除文件切片失败", e);
      }
    });
  }
  writeStream.end();
}
